from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import ensure_csrf_cookie
from django.shortcuts import HttpResponse, Http404, render
from django.core.handlers.wsgi import WSGIRequest
from django.views.decorators.http import require_GET
import json
# from hte.error.handle import error_page
from hte.error.models import HTEError
# from apps.account.models.users import UserRole
# from apps.analytics.tasks import on_view

from .models.template import Template
from .models.data import DataMeta, DataContent
from .models.dataset import DataSet

# Create your views here.


def add_template(req):
    action = req.GET.get('action')
    tid = req.GET.get('tid')
    return render(req, 'storage/template.html',
                  {'tid': tid,
                   'action': action})
    # return render(req, 'storage/template.html')


def add_data(req):
    action = req.GET.get('action')   # `add` or `modify`
    did = req.GET.get('did')
    return render(req, 'storage/add_data.html',
                  {'action': action,
                   'did': did})


# def show_data(req, did):
#         d = DataMeta.objects.get(pk=did)
#         context = dict(meta=d)
#         return render(req, 'storage/show_data.html',
#                       context=context)


def show_data(req, did):
    try:
        d = DataMeta.objects.get(pk=did)
        context = dict(meta=d)
        # context['content'] = get_iter_content(d.dc_id)
        # print(context)
        # on_view(did)
        return render(req, 'storage/show_data.html',
                      context=context)
    except DataMeta.DoesNotExist:
        raise Http404

@login_required
def my_template(req: WSGIRequest):
    return render(req, template_name='storage/my_template.html')

@login_required
def my_data(req):
    return render(req, 'storage/my_template.html')


def upload_dataset(req: WSGIRequest):
    return render(req, template_name='storage/upload_dataset.html')


def view_dataset(req: WSGIRequest, did):
    try:
        dataset = DataSet.objects.get(id=did)
        context = dict(meta=dataset)
        return render(req, 'storage/view_dataset.html', context=context)
    except DataMeta.DoesNotExist:
        raise Http404